<?php

namespace app\api\logic;

use app\common\exception\BusinessException;
use app\common\model\AppConfig;
use app\common\model\MpUser;
use app\common\service\UserService;

class MpMenu extends Mp
{
    /**
     * handler
     * @param $message
     * @return mixed
     */
    public function handler($message)
    {
        // 提取参数
        $fromUserName = $message['FromUserName'];

        // 保存用户信息
        $this->saveUser($fromUserName);

        // 解析用户输入参数
        $content = intval($message['Content'] ?? '');
        switch ($content) {
            case 1;
                // 搜题刷题
                return $this->getMcpLinkText();
                break;
            case 2:
                // 查看验证码
                return $this->verifyCodeHandler($message);
                break;
            case 3:
                // 签到送积分
                return $this->signHandler($message);
                break;
            case 4:
                // H5版本
                return $this->h5LinkHandler($message);
                break;
            case 5:
                return '加微信号 skr-web 提供论文代写服务';
                //return $this->getNotSupportText();
            default:
                return $this->getNotSupportText();
                break;
        }
    }

    /**
     * signHandler
     * @param $message
     * @return string
     * @throws
     */
    protected function signHandler($message): string
    {
        $fromUserName = $message['FromUserName'];
        $where = [
            'mp_openid' => $fromUserName
        ];
        $userInfo = app(\app\common\model\User::class)->where($where)->find();
        if (!$userInfo) {
            return '请先在小程序中绑定公众号';
        }
        try {
            $score = (new Sign())->mpConfirm($userInfo['id']);
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }
        return '签到成功,获得' . $score . '积分';
    }

    /**
     * h5LinkHandler
     * @param $message
     * @return string
     */
    protected function h5LinkHandler($message): string
    {
        // 提取参数
        $fromUserName = $message['FromUserName'];


        try {
            // 提取H5配置
            $appId = getAppId();
            $config = app(AppConfig::class)->getByIdAndType($appId, 'h5_config');

            // 查询用户
            $where = [
                'mp_openid' => $fromUserName
            ];
            $userInfo = app(\app\common\model\User::class)->where($where)->find();
            if (!$userInfo) {
                return $config['host'];
            }

            // 生成authKey
            $authKey = (new UserService())->buildAuthKey($userInfo['id']);

            // 返回
            return $config['host'] . '/#/pages/user/login/auth?authKey=' . $authKey;

        } catch (\Exception $exception) {
            return $exception->getMessage();
        }
    }

    /**
     * verifyCodeHandler
     * @param $message
     * @return string
     */
    protected function verifyCodeHandler($message): string
    {
        $verifyCode = $message['FromUserName'];
        return '您的验证码为：' . PHP_EOL . $verifyCode;
    }

    /**
     * textHandler
     * @param $message
     * @return string
     */
    protected function textHandler($message): string
    {
        // 提取参数
        $fromUserName = $message['FromUserName'];
        $content = trim($message['Content']);
        if ($content == 1) {
            return $this->getMcpLinkText();
        }
        if ($content == 2) {
            return '您的验证码为：' . PHP_EOL . $fromUserName;
        }
        if ($content == 5) {
            return $this->getH5LinkText();
        }


        return $this->welcome . PHP_EOL . $this->getMenuText();
    }

    /**
     * eventHandler
     * @param $messageEvent
     * @return string
     */
    protected function eventHandler($messageEvent): string
    {
        switch ($messageEvent) {
            case 'subscribe':
                return $this->welcome;
                break;
            default:
                return 'event 事件' . $messageEvent;
                break;
        }
    }

    /**
     * getMenuText
     * @return string
     */
    protected function getMenuText(): string
    {
        $text = '';
        foreach ($this->selectMenu as $key => $val) {
            $text .= $val . PHP_EOL;
        }
        return $text;
    }

    /**
     * saveUser
     * @param $openId
     * @return void
     * @throws
     */
    protected function saveUser($openId)
    {
        $where = [['openid', '=', $openId]];
        $count = app(MpUser::class)->where($where)->count();
        if (!$count) {
            $time = time();
            $saveData = [
                'openid' => $openId,
                'create_time' => $time,
                'update_time' => $time,
            ];
            $isInsert = app(MpUser::class)->insert($saveData);
            if (!$isInsert) {
                throw new BusinessException('保存用户信息失败');
            }
        }
    }


}